#'
#' Convert population/community object to and from ppp object in the spatstat package
#' 
#' @aliases pop_to_ppp ppp_to_pop com_to_ppp ppp_to_com
#'
#'
#' @usage
#' pop_to_ppp(pop)
#' ppp_to_pop(ppp,species)
#' com_to_ppp(com)
#' ppp_to_com(ppp)
#' 
#' @param pop a population object
#' @param com a community object
#' @param ppp a ppp object in the spatstat package
#' @param species a character of species name
#' 
#' 
#' @examples
#' set.seed(1)
#' 
#' pop=rpopulation(species="sp1",n=10,plotdim=c(10,10))
#' pop
#' ppp=pop_to_ppp(pop)
#' ppp
#' pop2=ppp_to_pop(ppp,"sp1")
#' pop2
#'
#' com=rcommunity(1:10,sample(1:20,10),plotdim=c(10,10))
#' com
#' ppp2=com_to_ppp(com)
#' ppp2
#' com2=ppp_to_com(ppp2)
#' com2
#' 
#'
#'

pop_to_ppp=function(pop){
  require("spatstat")
  plotdim=attr(pop,"plotdim")
  return(ppp(x=pop$x,y=pop$y,window=owin(c(0,plotdim[1]),c(0,plotdim[2])),check=FALSE,drop=FALSE))
}

ppp_to_pop=function(ppp,species){
  plotdim=c(ppp$win$xrange[2],ppp$win$yrange[2])
  return(population(species=species,x=ppp$x,y=ppp$y,plotdim=plotdim))
}

#' @export
com_to_ppp=function(com){
  plotdim=attr(com,"plotdim")
  traits=com[,-c(2:3)]
  return(ppp(x=com$x,y=com$y,window=owin(c(0,plotdim[1]),c(0,plotdim[2])),marks=traits,check=FALSE,drop=FALSE))
}

ppp_to_com=function(ppp){
  plotdim=c(ppp$win$xrange[2],ppp$win$yrange[2])
  return(community(species=ppp$marks$species,x=ppp$x,y=ppp$y,plotdim=plotdim))
}
